package com.business.business.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.business.business.common.base.BaseService;
import com.business.business.model.Business;
import com.business.business.model.BusinessFirefightingplan;
import com.business.business.model.BusinessLegaldocuments;
import com.business.business.model.BusinessRulesandregulations;
import com.business.business.support.model.RespEntity;
import com.business.business.support.mybatisplus.QueryWrapper;
import com.business.business.support.utils.requestutil.HttpRequestUtil;
import com.business.business.web.mapper.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Yang yu
 * @version 1.0
 * @date 2020/7/18 15:25
 */
@Service
public class BusinessEvaluationService extends BaseService {
    @Resource
    private BusinessMapper businessMapper;

    @Resource
    private BusinessLegaldocumentsMapper businessLegaldocumentsMapper;

    @Resource
    private BusinessRulesandregulationsMapper businessRulesandregulationsMapper;

    @Resource
    private BusinessFirefightingplanMapper businessFirefightingplanMapper;

    @Resource
    private BusinessFiretrainingMapper businessFiretrainingMapper;


    /**
     * 单位评估服务
     * @param jsonParam
     * @return
     */
    public RespEntity getBusinessEvaluation(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String businessId = null;

        if (userType.equals("1")) {
            businessId = jsonParam.getStr("businessId");
        } else {
            businessId = homeId;
        }
        jsonParam.put("businessId",businessId);
        //单位基本信息
        Business business = businessMapper.selectOne(new QueryWrapper<Business>().eq("id",businessId));
        if (business == null){
            return RespEntity.fail("单位不存在!");
        }
        //组装最终数据
        Map<String,Object> totalMap = new HashMap<>();
        //组装列表
        List<Map<String,String>> list = new ArrayList<>();
        //总成绩
        int totalScore = 100;
        //评估成绩
        int result = 0;
        //消防安全合法性 10
        int fanallyScore = 10;//最终得分
        String scoreSituation = "得分情况:已上传相关消防法律文书。";
        String remark = "单位使用的建筑物、场所，经公安机关消防机构依法审核、验收、竣工验收消防备案合格；属于公众聚集场所的单位，应经公安机关消防机构依法进行消防安全检查合格。";
        int businessLegaldocuments = businessLegaldocumentsMapper.selectCount(new QueryWrapper<BusinessLegaldocuments>().eq("business_id",businessId));
        if (businessLegaldocuments == 0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未上传相关消防法律文书,扣10分。";
        }
        result = result + fanallyScore;
        list = getList("消防安全合法性(10分)",remark,scoreSituation,fanallyScore,list);
        //消防安全制度、消防安全操作规程制定 10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况:已制定规章制度。";
        remark = "能够针对本单位实际制定相关管理制度和操作规程。每项管理制度和操作规程内容符合对应条款要求。员工对本单位管理制度和操作规程掌握熟练。";
        int businessRulesandregulations = businessRulesandregulationsMapper.selectCount(new QueryWrapper<BusinessRulesandregulations>().eq("business_id",businessId));
        if (businessRulesandregulations == 0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未制定规章制度,扣10分。";
        }
        result = result + fanallyScore;
        list = getList("消防安全制度、消防安全操作规程制定(10分)",remark,scoreSituation,fanallyScore,list);
        //落实单位消防安全责任人和消防安全管理人10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：";
        remark = "明确消防安全责任人、管理人，确定、变更后3日内报当地公安机关消防机构备案；熟练掌握自身消防安全职责；人员密集场所、易燃易爆危险品企业火灾高危单位的消防安全管理人取得注册消防工程师资格。成立消防工作领导机构并按要求开展工作。";
        if (StrUtil.isBlank(business.getSafeResponPersonName())){
            fanallyScore = fanallyScore-5;
            scoreSituation = scoreSituation + "消防安全负责人账号未建立，扣5分;";
        }else{
            scoreSituation = scoreSituation + "消防安全负责人账号已建立;";
        }
        if (StrUtil.isBlank(business.getSafeManagePersonName())){
            fanallyScore = fanallyScore-5;
            scoreSituation = scoreSituation + "消防安全管理人账号未建立，扣5分;";
        }
        else{
            scoreSituation = scoreSituation + "消防安全管理人账号已建立;";
        }
        result = result + fanallyScore;
        list = getList("落实单位消防安全责任人和消防安全管理人(10分)",remark,fanallyScore == 10? scoreSituation + "已落实单位消防安全责任人和消防安全管理人。":scoreSituation.substring(0,scoreSituation.length()-1) + "。",fanallyScore,list);
        //单位基础信息、平面图完整 10
        fanallyScore = 12;//最终得分
        scoreSituation = "得分情况：";
        remark = "单位应维护好本单位的基础信息真实有效。";
        if (StrUtil.isBlank(business.getAddr())){
            fanallyScore = fanallyScore-4;
            scoreSituation = scoreSituation + "未填写详细地址，扣4分;";
        }else{
            scoreSituation = scoreSituation + "已填写详细地址;";
        }
        if (StrUtil.isBlank(business.getLat())||StrUtil.isBlank(business.getLon())){
            fanallyScore = fanallyScore-4;
            scoreSituation = scoreSituation + "未在地图上定位，扣4分;";
        }else{
            scoreSituation = scoreSituation + "已在地图上定位;";
        }
        int businessFirefightingplan = businessFirefightingplanMapper.selectCount(new QueryWrapper<BusinessFirefightingplan>().eq("business_id",businessId));
        if (businessFirefightingplan == 0){
            fanallyScore = fanallyScore-4;
            scoreSituation = scoreSituation + "未上传平面图，扣4分;";
        }else{
            scoreSituation = scoreSituation + "已上传平面图;";
        }
        result = result + fanallyScore;
        list = getList("单位基础信息、平面图完整(12分)",remark,fanallyScore == 10? scoreSituation + "已填写详细地址;已在地图上定位;已上传平面图。":scoreSituation.substring(0,scoreSituation.length()-1) + "。",fanallyScore,list);
        //消防安全培训 10
        int businessFiretraining = businessFiretrainingMapper.selectCount(jsonParam);
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：半年内已进行安全培训。";
        remark = "开展多种形式内部、对外消防宣传，在消防宣传日、重大节假日或重大活动期间应开展消防宣传活动。消防安全培训应列入年度工作计划。新上岗和进入新岗位的员工应进行岗前消防安全培训。在岗人员应按规定进行消防安全教育培训。进行电焊、气焊等具有火灾危险作业的人员和自动消防系统的操作人员应持证上岗。员工“一懂三会”掌握熟练。";
        if (businessFiretraining == 0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未制定规章制度,扣10分。";
        }
        result = result + fanallyScore;
        list = getList("消防安全培训(10分)",remark,scoreSituation,fanallyScore,list);
        //微型消防站8
        fanallyScore = 8;//最终得分
        scoreSituation = "得分情况：一般单位和九小场所此项不做要求。";
        remark = "应建立微型消防站；应当组织消防员队伍。";
        result = result + fanallyScore;
        list = getList("微型消防站(8分)",remark,scoreSituation,fanallyScore,list);
        //隐患整改 10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：不存在超期未整改隐患。";
        remark = "对发现的隐患及时整改。隐患程序符合规定要求，隐患整改方案完整、齐全。";
        int hiddenDanger =  restEvaluation(jsonParam,"check","getHiddendangerCount","check");

        if (hiddenDanger>0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:存在超期未整改的隐患,扣10分。";
        }
        result = result + fanallyScore;
        list = getList("隐患整改(10分)",remark,scoreSituation,fanallyScore,list);
        //智慧用电安全 10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：已接入智慧用电安全监测系统。";
        remark = "接入智慧用电安全监测系统加10分。";
        JSONObject elec = new JSONObject();
        elec.put("businessId",businessId);
        elec.put("deviceClassify","1");
        int electricity =  restEvaluation(elec,"firefightingiot","getDeviceCount","device");
        if (electricity<=0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未接入智慧用电安全监测系统,扣10分。";
        }
        result = result + fanallyScore;
        list = getList("智慧用电安全(10分)",remark,scoreSituation,fanallyScore,list);
        //重点部位管理(可视化)10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：已接入重点部位可视化监控系统。";
        remark = "接入重点部位可视化监控系统加10分。";
        JSONObject visua = new JSONObject();
        visua.put("businessId",businessId);
        visua.put("deviceClassify","6");
        int Visualization =  restEvaluation(visua,"firefightingiot","getDeviceCount","device");
        if (Visualization<=0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未接入重点部位可视化监控系统,扣10分。";
        }
        result = result + fanallyScore;
        list = getList("重点部位管理(10分)",remark,scoreSituation,fanallyScore,list);
        //建筑消防用水10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：已接入建筑消防用水监测系统。";
        remark = "接入建筑消防用水监测系统加10分。";
        JSONObject water = new JSONObject();
        water.put("businessId",businessId);
        water.put("deviceClassify","2");
        int waters = restEvaluation(water,"firefightingiot","getDeviceCount","device");
        if (waters<=0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未接入建筑消防用水监测系统,扣10分。";
        }
        result = result + fanallyScore;
        list = getList("建筑消防用水(10分)",remark,scoreSituation,fanallyScore,list);
        totalMap.put("list",list);
        totalMap.put("grade",getGrade(result));
        totalMap.put("time", DateUtil.now());
        totalMap.put("score", result);
        totalMap.put("subtractScore", totalScore - result);
        return RespEntity.success(totalMap);
    }
    /**
     * @Author YangYu
     * @Description 根据单位ID查询
     * @Date Created in 下午4:27 2025/4/23
     * @Param [businessId]
     */

    public Integer getBusinessEvaluation(Business business) {
        String businessId = business.getId();
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("businessId",businessId);
        //组装最终数据
        Map<String,Object> totalMap = new HashMap<>();
        //总成绩
        int totalScore = 100;
        //评估成绩
        int result = 0;
        //消防安全合法性 10
        int fanallyScore = 10;//最终得分
        String scoreSituation = "得分情况:已上传相关消防法律文书。";
        String remark = "单位使用的建筑物、场所，经公安机关消防机构依法审核、验收、竣工验收消防备案合格；属于公众聚集场所的单位，应经公安机关消防机构依法进行消防安全检查合格。";
        int businessLegaldocuments = businessLegaldocumentsMapper.selectCount(new QueryWrapper<BusinessLegaldocuments>().eq("business_id",businessId));
        if (businessLegaldocuments == 0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未上传相关消防法律文书,扣10分。";
        }
        result = result + fanallyScore;
        //消防安全制度、消防安全操作规程制定 10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况:已制定规章制度。";
        remark = "能够针对本单位实际制定相关管理制度和操作规程。每项管理制度和操作规程内容符合对应条款要求。员工对本单位管理制度和操作规程掌握熟练。";
        int businessRulesandregulations = businessRulesandregulationsMapper.selectCount(new QueryWrapper<BusinessRulesandregulations>().eq("business_id",businessId));
        if (businessRulesandregulations == 0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未制定规章制度,扣10分。";
        }
        result = result + fanallyScore;
        //落实单位消防安全责任人和消防安全管理人10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：";
        remark = "明确消防安全责任人、管理人，确定、变更后3日内报当地公安机关消防机构备案；熟练掌握自身消防安全职责；人员密集场所、易燃易爆危险品企业火灾高危单位的消防安全管理人取得注册消防工程师资格。成立消防工作领导机构并按要求开展工作。";
        if (StrUtil.isBlank(business.getSafeResponPersonName())){
            fanallyScore = fanallyScore-5;
            scoreSituation = scoreSituation + "消防安全负责人账号未建立，扣5分;";
        }else{
            scoreSituation = scoreSituation + "消防安全负责人账号已建立;";
        }
        if (StrUtil.isBlank(business.getSafeManagePersonName())){
            fanallyScore = fanallyScore-5;
            scoreSituation = scoreSituation + "消防安全管理人账号未建立，扣5分;";
        }
        else{
            scoreSituation = scoreSituation + "消防安全管理人账号已建立;";
        }
        result = result + fanallyScore;
        //单位基础信息、平面图完整 10
        fanallyScore = 12;//最终得分
        scoreSituation = "得分情况：";
        remark = "单位应维护好本单位的基础信息真实有效。";
        if (StrUtil.isBlank(business.getAddr())){
            fanallyScore = fanallyScore-4;
            scoreSituation = scoreSituation + "未填写详细地址，扣4分;";
        }else{
            scoreSituation = scoreSituation + "已填写详细地址;";
        }
        if (StrUtil.isBlank(business.getLat())||StrUtil.isBlank(business.getLon())){
            fanallyScore = fanallyScore-4;
            scoreSituation = scoreSituation + "未在地图上定位，扣4分;";
        }else{
            scoreSituation = scoreSituation + "已在地图上定位;";
        }
        int businessFirefightingplan = businessFirefightingplanMapper.selectCount(new QueryWrapper<BusinessFirefightingplan>().eq("business_id",businessId));
        if (businessFirefightingplan == 0){
            fanallyScore = fanallyScore-4;
            scoreSituation = scoreSituation + "未上传平面图，扣4分;";
        }else{
            scoreSituation = scoreSituation + "已上传平面图;";
        }
        result = result + fanallyScore;
        //消防安全培训 10
        int businessFiretraining = businessFiretrainingMapper.selectCount(jsonParam);
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：半年内已进行安全培训。";
        remark = "开展多种形式内部、对外消防宣传，在消防宣传日、重大节假日或重大活动期间应开展消防宣传活动。消防安全培训应列入年度工作计划。新上岗和进入新岗位的员工应进行岗前消防安全培训。在岗人员应按规定进行消防安全教育培训。进行电焊、气焊等具有火灾危险作业的人员和自动消防系统的操作人员应持证上岗。员工“一懂三会”掌握熟练。";
        if (businessFiretraining == 0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未制定规章制度,扣10分。";
        }
        result = result + fanallyScore;
        //微型消防站8
        fanallyScore = 8;//最终得分
        scoreSituation = "得分情况：一般单位和九小场所此项不做要求。";
        remark = "应建立微型消防站；应当组织消防员队伍。";
        result = result + fanallyScore;
        //隐患整改 10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：不存在超期未整改隐患。";
        remark = "对发现的隐患及时整改。隐患程序符合规定要求，隐患整改方案完整、齐全。";
        int hiddenDanger =  restEvaluation(jsonParam,"check","getHiddendangerCount","check");

        if (hiddenDanger>0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:存在超期未整改的隐患,扣10分。";
        }
        result = result + fanallyScore;
        //智慧用电安全 10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：已接入智慧用电安全监测系统。";
        remark = "接入智慧用电安全监测系统加10分。";
        JSONObject elec = new JSONObject();
        elec.put("businessId",businessId);
        elec.put("deviceClassify","1");
        int electricity =  restEvaluation(elec,"firefightingiot","getDeviceCount","device");
        if (electricity<=0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未接入智慧用电安全监测系统,扣10分。";
        }
        result = result + fanallyScore;
        //重点部位管理(可视化)10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：已接入重点部位可视化监控系统。";
        remark = "接入重点部位可视化监控系统加10分。";
        JSONObject visua = new JSONObject();
        visua.put("businessId",businessId);
        visua.put("deviceClassify","6");
        int Visualization =  restEvaluation(visua,"firefightingiot","getDeviceCount","device");
        if (Visualization<=0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未接入重点部位可视化监控系统,扣10分。";
        }
        result = result + fanallyScore;
        //建筑消防用水10
        fanallyScore = 10;//最终得分
        scoreSituation = "得分情况：已接入建筑消防用水监测系统。";
        remark = "接入建筑消防用水监测系统加10分。";
        JSONObject water = new JSONObject();
        water.put("businessId",businessId);
        water.put("deviceClassify","2");
        int waters = restEvaluation(water,"firefightingiot","getDeviceCount","device");
        if (waters<=0){
            fanallyScore = fanallyScore-10;
            scoreSituation = "得分情况:未接入建筑消防用水监测系统,扣10分。";
        }
        result = result + fanallyScore;
        totalMap.put("grade",getGrade(result));
        totalMap.put("time", DateUtil.now());
        totalMap.put("score", result);
        totalMap.put("subtractScore", totalScore - result);
        return result;
    }
    /**
     * 评估详情
     * @param title
     * @param remark
     * @param reason
     * @param fanallyScore
     * @param list
     * @return
     */
    public List<Map<String,String>> getList(String title,String remark,String reason,int fanallyScore, List<Map<String,String>> list){
        Map<String,String> map = new HashMap<>();
        map.put("title",title);
        map.put("remark",remark);
        map.put("reason",reason);
        map.put("fanallyScore","得分:" + fanallyScore);
        list.add(map);
        return list;
    }

    /**
     * 评估等级
     * @param score
     * @return
     */
    public String getGrade(int score){
        String grade = "";
        if(score<=100 && score>=90){
            grade = "A";
        }else if (score<=90 && score>=80){
            grade = "B";
        }else if (score<=80 && score>=70){
            grade = "C";
        }else if (score<=70 && score>=0){
            grade = "D";
        }
        return grade;
    }
}
